package chapter2.eg1;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import org.junit.Test;

public class EchoServer {

  @Test
  public void testServer() throws IOException {
    ServerSocketChannel server = ServerSocketChannel.open();
    server.bind(new InetSocketAddress(8080));
    while (true) {
      SocketChannel channel = server.accept();
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      channel.read(buffer);
      handle(buffer);
      response(channel);
    }
  }

  private void response(SocketChannel channel) throws IOException {
    ByteBuffer buffer = ByteBuffer.wrap(("Hello, I'm server. It's: " + new Date()).getBytes());
    channel.write(buffer);
    channel.close();
  }

  private void handle(ByteBuffer buffer) {
    buffer.flip();
    byte[] bytes = new byte[buffer.remaining()];
    buffer.get(bytes);
    System.out.println("Server receives message: ");
    System.out.println(new String(bytes, StandardCharsets.UTF_8));
  }
}
